<template>
    <div class="security">
        <van-nav-bar title="账号安全" left-text="返回" left-arrow @click-left="onClickLeft" />

        <div class="security-content">
            <!-- 安全信息卡片 -->
            <van-cell-group inset class="security-group" title="安全信息">
                <van-cell title="手机号" :value="securityInfo.phoneVerified ? '已验证' : '未验证'" is-link
                    @click="handleVerifyPhone" center>
                    <template #right-icon>
                        <van-tag v-if="securityInfo.phoneVerified" type="success">已保护</van-tag>
                        <van-tag v-else type="danger">未保护</van-tag>
                    </template>
                </van-cell>
                <van-cell title="邮箱" :value="securityInfo.emailVerified ? '已验证' : '未验证'" is-link
                    @click="handleVerifyEmail" center>
                    <template #right-icon>
                        <van-tag v-if="securityInfo.emailVerified" type="success">已保护</van-tag>
                        <van-tag v-else type="danger">未保护</van-tag>
                    </template>
                </van-cell>
                <van-cell title="密码管理" is-link @click="showPasswordPopup = true" />
            </van-cell-group>

            <!-- 安全设置选项 -->
            <van-cell-group inset class="security-group" title="安全设置">
                <van-cell center title="两步验证">
                    <template #right-icon>
                        <van-switch v-model="twoFactorAuth" @change="handleTwoFactorChange" size="24" />
                    </template>
                </van-cell>
                <van-cell title="登录设备管理" is-link @click="showDevicePopup = true" />
                <van-cell title="实名认证" is-link />
            </van-cell-group>

            <!-- 安全中心 -->
            <van-cell-group inset class="security-group" title="安全中心">
                <van-cell title="账号注销" is-link />
                <van-cell title="紧急联系人设置" is-link />
            </van-cell-group>
        </div>

        <!-- 密码修改弹窗 -->
        <van-popup v-model:show="showPasswordPopup" round position="bottom" :style="{ height: '45%' }">
            <div class="popup-content">
                <div class="popup-title">修改密码</div>
                <van-form @submit="handlePasswordChange">
                    <van-field v-model="passwordForm.oldPassword" type="password" name="oldPassword" label="当前密码"
                        placeholder="请输入当前密码" :rules="[{ required: true, message: '请输入当前密码' }]" />
                    <van-field v-model="passwordForm.newPassword" type="password" name="newPassword" label="新密码"
                        placeholder="请输入新密码" :rules="[{ required: true, message: '请输入新密码' }]" />
                    <van-field v-model="passwordForm.confirmPassword" type="password" name="confirmPassword"
                        label="确认密码" placeholder="请再次输入新密码" :rules="[
                            { required: true, message: '请再次输入新密码' },
                            { validator: validatePasswordConfirm, message: '两次密码不一致' }
                        ]" />
                    <div class="popup-buttons">
                        <van-button block type="primary" native-type="submit" round color="#ff9854">确认修改</van-button>
                        <van-button block type="default" round @click="showPasswordPopup = false">取消</van-button>
                    </div>
                </van-form>
            </div>
        </van-popup>

        <!-- 登录设备管理弹窗 -->
        <van-popup v-model:show="showDevicePopup" round position="bottom" :style="{ height: '60%' }">
            <div class="popup-content">
                <div class="popup-title">登录设备管理</div>
                <van-list class="device-list">
                    <van-cell v-for="device in securityInfo.loginDevices" :key="device.id" :title="device.deviceName">
                        <template #label>
                            <div class="device-info">
                                <div>上次登录：{{ device.lastLogin }}</div>
                                <div>登录地点：{{ device.location }}</div>
                            </div>
                        </template>
                        <template #right-icon>
                            <van-button size="small" type="danger"
                                @click="handleLogoutDevice(device.id)">退出登录</van-button>
                        </template>
                    </van-cell>
                </van-list>
                <div class="popup-buttons">
                    <van-button block type="default" round @click="showDevicePopup = false">关闭</van-button>
                </div>
            </div>
        </van-popup>

        <!-- 验证弹窗 -->
        <van-popup v-model:show="showVerifyPopup" round position="bottom" :style="{ height: '40%' }">
            <div class="popup-content">
                <div class="popup-title">{{ verifyTitle }}</div>
                <van-form @submit="handleVerifySubmit">
                    <van-field v-model="verifyCode" name="verifyCode" :label="verifyLabel" placeholder="请输入验证码"
                        :rules="[{ required: true, message: '请输入验证码' }]">
                        <template #button>
                            <van-button size="small" type="primary" color="#ff9854" @click="sendVerifyCode"
                                :disabled="countdown > 0">
                                {{ countdown > 0 ? `${countdown}秒后重新获取` : '获取验证码' }}
                            </van-button>
                        </template>
                    </van-field>
                    <div class="popup-buttons">
                        <van-button block type="primary" native-type="submit" round color="#ff9854">提交验证</van-button>
                        <van-button block type="default" round @click="showVerifyPopup = false">取消</van-button>
                    </div>
                </van-form>
            </div>
        </van-popup>
    </div>
</template>

<script setup>
import { ref, computed, onMounted } from 'vue'
import { useRouter } from 'vue-router'
import { showToast, showSuccessToast, showFailToast, showLoadingToast, closeToast } from 'vant'
import useProfileStore from '@/stores/modules/profile'

const router = useRouter()
const profileStore = useProfileStore()
const securityInfo = computed(() => profileStore.securityInfo)

// 双因素认证开关状态
const twoFactorAuth = ref(false)

// 弹窗控制
const showPasswordPopup = ref(false)
const showDevicePopup = ref(false)
const showVerifyPopup = ref(false)

// 验证表单数据
const verifyTitle = ref('')
const verifyLabel = ref('')
const verifyType = ref('')
const verifyCode = ref('')
const countdown = ref(0)

// 密码表单
const passwordForm = ref({
    oldPassword: '',
    newPassword: '',
    confirmPassword: ''
})

// 初始化数据
onMounted(async () => {
    await profileStore.fetchSecuritySettings()
    twoFactorAuth.value = securityInfo.value.twoFactorAuth
})

// 返回按钮
const onClickLeft = () => {
    router.back()
}

// 密码确认验证
const validatePasswordConfirm = (value) => {
    return value === passwordForm.value.newPassword
}

// 处理双因素认证状态改变
const handleTwoFactorChange = async (checked) => {
    showLoadingToast({
        message: checked ? '开启中...' : '关闭中...',
        forbidClick: true,
        duration: 0
    })

    try {
        const result = await profileStore.updateSecurity({ twoFactorAuth: checked })
        if (result.success) {
            showSuccessToast(result.message)
        } else {
            twoFactorAuth.value = !checked
            showFailToast(result.message)
        }
    } catch (error) {
        twoFactorAuth.value = !checked
        showFailToast('操作失败')
    } finally {
        closeToast()
    }
}

// 处理密码修改
const handlePasswordChange = async () => {
    if (passwordForm.value.newPassword !== passwordForm.value.confirmPassword) {
        showFailToast('两次密码输入不一致')
        return
    }

    showLoadingToast({
        message: '修改中...',
        forbidClick: true,
        duration: 0
    })

    try {
        const result = await profileStore.updateSecurity({
            passwordLastChanged: formatDate(new Date())
        })

        if (result.success) {
            showSuccessToast('密码修改成功')
            showPasswordPopup.value = false
            // 清空表单
            passwordForm.value = {
                oldPassword: '',
                newPassword: '',
                confirmPassword: ''
            }
        } else {
            showFailToast(result.message)
        }
    } catch (error) {
        showFailToast('密码修改失败')
    } finally {
        closeToast()
    }
}

// 处理设备退出登录
const handleLogoutDevice = async (deviceId) => {
    showLoadingToast({
        message: '操作中...',
        forbidClick: true,
        duration: 0
    })

    try {
        // 过滤设备列表，模拟退出登录
        const updatedDevices = securityInfo.value.loginDevices.filter(device => device.id !== deviceId)
        const result = await profileStore.updateSecurity({
            loginDevices: updatedDevices
        })

        if (result.success) {
            showSuccessToast('设备已退出登录')
        } else {
            showFailToast(result.message)
        }
    } catch (error) {
        showFailToast('操作失败')
    } finally {
        closeToast()
    }
}

// 处理手机验证
const handleVerifyPhone = () => {
    verifyTitle.value = '手机验证'
    verifyLabel.value = '手机验证码'
    verifyType.value = 'phone'
    showVerifyPopup.value = true
}

// 处理邮箱验证
const handleVerifyEmail = () => {
    verifyTitle.value = '邮箱验证'
    verifyLabel.value = '邮箱验证码'
    verifyType.value = 'email'
    showVerifyPopup.value = true
}

// 发送验证码
const sendVerifyCode = () => {
    showLoadingToast({
        message: '发送中...',
        forbidClick: true,
        duration: 1500
    })

    // 倒计时
    countdown.value = 60
    const timer = setInterval(() => {
        countdown.value--
        if (countdown.value <= 0) {
            clearInterval(timer)
        }
    }, 1000)

    // 模拟发送验证码
    setTimeout(() => {
        closeToast()
        showSuccessToast('验证码已发送')
    }, 1500)
}

// 提交验证
const handleVerifySubmit = async () => {
    if (verifyCode.value.length !== 6) {
        showFailToast('请输入正确的验证码')
        return
    }

    showLoadingToast({
        message: '验证中...',
        forbidClick: true,
        duration: 0
    })

    try {
        // 根据验证类型更新不同的字段
        const updateData = {}
        if (verifyType.value === 'phone') {
            updateData.phoneVerified = true
        } else if (verifyType.value === 'email') {
            updateData.emailVerified = true
        }

        const result = await profileStore.updateSecurity(updateData)

        if (result.success) {
            showSuccessToast('验证成功')
            showVerifyPopup.value = false
            verifyCode.value = ''
        } else {
            showFailToast(result.message)
        }
    } catch (error) {
        showFailToast('验证失败')
    } finally {
        closeToast()
    }
}

// 格式化日期
const formatDate = (date) => {
    const year = date.getFullYear()
    const month = String(date.getMonth() + 1).padStart(2, '0')
    const day = String(date.getDate()).padStart(2, '0')
    return `${year}-${month}-${day}`
}
</script>

<style lang="less" scoped>
.security {
    background-color: #f7f8fa;
    min-height: 100vh;
}

.security-content {
    padding: 12px 0;
}

.security-group {
    margin-bottom: 12px;
}

.popup-content {
    padding: 20px 16px;
}

.popup-title {
    font-size: 18px;
    font-weight: bold;
    text-align: center;
    margin-bottom: 20px;
}

.popup-buttons {
    margin-top: 24px;
    display: flex;
    flex-direction: column;
    gap: 12px;
}

.device-list {
    margin-bottom: 16px;
    max-height: 300px;
    overflow-y: auto;
}

.device-info {
    font-size: 12px;
    color: #999;
    line-height: 1.5;
}
</style>